/*
 * @Description: 将本地路由导出为可用于导入线上路由的文件，需要请手动调用
 * @Version: 1.0
 * @Autor: chen_yt
 * @Date: 2022-08-25 15:34:57
 * @LastEditors: chen_yt
 * @LastEditTime: 2022-08-25 15:36:18
 */

import { exportFile } from '@/utils/file'
/**
 * @description: 将本地路由导出为可用于导入线上路由的文件
 *               默认不添加特殊属性
 *               若想进行特殊处理请自行修改newItem的属性计算方法
 * @param {Array} routes 
 */
export const exportLocalRoute = function (routes) {

    let transRouteToExportItem = async function (route) {

        let newItem = {
            path: route.path,
            redirect: route.redirect,
            code: route.name,
            title: (route.meta && route.meta.title) ? route.meta.title : route.name,
            meta: JSON.stringify({ ...route.meta }),
            children: [],
            hidden: false,
            isAuth: false,
            icon: '',
        }

        if (route.component && typeof (route.component) == 'function') {
            let result = await route.component()
            newItem.component = result.default.__file.replace(/src\/modules(.*)/, '$1')
        }

        if (route.children) {
            for (let i = 0; i < route.children.length; i++) {
                let child = await transRouteToExportItem(route.children[i])
                newItem.children.push(child)
            }
        }
        else {
            delete newItem.children
        }

        return newItem
    }

    let exportRoute = routes.map(item => {
        return transRouteToExportItem(item)
    })

    Promise.all(exportRoute).then((res) => {
        console.log(JSON.stringify(res))

        let response = {
            data: JSON.stringify(res),
            headers: { 'content-disposition': 'attachment; filename="localMenus.json"' }
        }
        exportFile(response)
    })
}
